package com.fare.taluo.auth.domain.repository.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.dayatang.hibernate.EntityRepositoryHibernate;
import com.fare.taluo.auth.domain.UserInfoLogEntity;
import com.fare.taluo.auth.domain.repository.UserInfoLogRepositry;
@Repository
public class UserInfoLogRepositryImpl extends EntityRepositoryHibernate implements UserInfoLogRepositry{

	/**
	 * @return entity
	 * @param userName
	*/
	@Override
	public UserInfoLogEntity checkUserNmaeLogin(String userName) {
		List<Object> params = new ArrayList<Object>();
		StringBuffer hql=new StringBuffer(" from UserInfoLogEntity u where u.userName=?");
		if(userName !=null && !userName.equals("")){
			params.add(userName);
		}
		hql.append(" order by u.createTime desc");
		List<UserInfoLogEntity> list =new ArrayList<UserInfoLogEntity>();
		list=this.find(hql.toString(),params.toArray(),UserInfoLogEntity.class);
		if(list.size()>0){
			return list.get(0);
		}else return null;
		
	}

	@Override
	public void saveOrUpdate(UserInfoLogEntity entity) {
		Session session = super.getSession();
		if(entity.getId() ==null || entity.getId()<=0){
			session.save(entity);
		}else{
			session.merge(entity);
//			session.update(entity);
		}
		
	}

	/**
	 * 计数器
	*/
	@Override
	public int countUserOnline() {
		Session session = super.getSession();
		Query query=session.createSQLQuery("select count(*) from sys_userinfo_log t where t.logout_time is null and t.online_time is null");
		return Integer.parseInt(query.list().get(0).toString());
	}

	@Override
	public List<UserInfoLogEntity> findAll(Date loginTime, Date logoutTime) {
		List<Object> params = new ArrayList<Object>();
		StringBuffer hql=new StringBuffer(" from UserInfoLogEntity u where 1=1");
		if(loginTime !=null){
			hql.append(" and  u.loginTime >=?");
			params.add(loginTime);
		}
		if(logoutTime !=null){
			hql.append(" and  u.logoutTime <=?");
			params.add(logoutTime);
		}
		hql.append(" ORDER BY u.createTime desc");
		List<UserInfoLogEntity> list =new ArrayList<UserInfoLogEntity>();
		list=this.find(hql.toString(),params.toArray(),UserInfoLogEntity.class);
		return list;
	}

	/**
	 * 重启系统后，对用户登录信息进行一次的清理操作
	 */
	@Override
	public void systemUpdate() {
		Session session = super.getSession();
		Query query=session.createSQLQuery("update sys_userinfo_log set logout_time=NOW() where logout_time is null and online_time is null");
		query.executeUpdate();
	}
}
